<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tag;
use App\Services\TagService;
use App\Http\Requests\StoreTagRequest;
use App\Http\Requests\UpdateTagRequest;
use Illuminate\Http\Request;
use Inertia\Inertia;

/**
 * 标签管理控制器
 * 
 * 职责：
 * - 处理标签管理相关的HTTP请求
 * - 调用 TagService 处理业务逻辑
 * - 返回视图和重定向
 */
class TagController extends Controller
{
    /**
     * 标签服务
     * 
     * @var TagService
     */
    protected TagService $tagService;

    /**
     * 构造器
     */
    public function __construct(TagService $tagService)
    {
        $this->tagService = $tagService;
    }
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // 调用服务层获取标签列表
        $tags = $this->tagService->getList(
            $request->only(['search'])
        );

        return Inertia::render('Admin/Tags/Index', [
            'tags' => [
                'data' => $tags->items(),
                'meta' => [
                    'current_page' => $tags->currentPage(),
                    'from' => $tags->firstItem(),
                    'last_page' => $tags->lastPage(),
                    'links' => $tags->linkCollection()->toArray(),
                    'path' => $tags->path(),
                    'per_page' => $tags->perPage(),
                    'to' => $tags->lastItem(),
                    'total' => $tags->total(),
                ],
            ],
            'filters' => $request->only(['search'])
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('Admin/Tags/Create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreTagRequest $request)
    {
        // 验证已通过，调用服务层创建标签
        Tag::create($request->validated());

        return redirect()->route('admin.tags.index')
            ->with('message', '标签创建成功！');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Tag $tag)
    {
        return Inertia::render('Admin/Tags/Edit', [
            'tag' => $tag
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateTagRequest $request, Tag $tag)
    {
        // 验证已通过，更新标签
        $tag->update($request->validated());

        return redirect()->route('admin.tags.index')
            ->with('message', '标签更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Tag $tag)
    {
        // 检查标签下是否有文章
        if ($tag->posts()->exists()) {
            return back()->with('error', '该标签下还有文章，无法删除！');
        }

        $tag->delete();

        return back()->with('message', '标签删除成功！');
    }
} 